package com.lemon.conf.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.lemon.conf.MyException;
import com.lemon.conf.MyYml;
import com.lemon.conf.content.SpringContextUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;


/**
 * @author xmc
 * @date 2014-9-19 上午10:50:44
 * @note 
 */
public class RedisUtil {
	
	private static Logger log = LoggerFactory.getLogger(RedisUtil.class);
	
	public  static  MyYml yml = (MyYml)SpringContextUtil.getBean("myYml");
	
	public static final String key_before = "cityRun:";

	public static  JedisPool jedisPool =  null;
	/*static{
		ip = Configuration.readConfigString("redis_server_ip");
		System.out.println(ip); 
		port = Integer.parseInt(Configuration.readConfigString("redis_server_port"));
	}*/  
    public static JedisPool getInstance() {
        if (null == jedisPool) {
        	synchronized(RedisUtil.class){
//				if (jedisPool == null) {
		            JedisPoolConfig  jedispool_config = new JedisPoolConfig();
		            //最大活动对象个数
		            jedispool_config.setMaxTotal(Integer.parseInt(yml.getMaxActive()));;
		           // jedispool_config.setMaxActive(500);
		            //对象最大空闲时间
		            jedispool_config.setMaxIdle(Integer.parseInt(yml.getMaxIdle()));
		            //获取对象时最大等待时间
		            jedispool_config.setMaxWaitMillis(3000L);
		            //jedispool_config.setMaxWait(3000L);
		            jedispool_config.setTestOnBorrow(false);
		            
		            //jedisPool = new JedisPool(jedispool_config, ip, port,100000);
//		            jedisPool = new JedisPool(jedispool_config, "127.0.0.1", 6379,Protocol.DEFAULT_TIMEOUT,"");
		            if (!yml.getPassword().equals("")&&yml.getPassword()!=null) {
		            	jedisPool = new JedisPool(jedispool_config, yml.getHost(),Integer.parseInt( yml.getPort()),Protocol.DEFAULT_TIMEOUT,yml.getPassword());
					}else{
						jedisPool = new JedisPool(jedispool_config, yml.getHost(),Integer.parseInt( yml.getPort()),Protocol.DEFAULT_TIMEOUT);
					}
				}
//        	}   
		}
        return jedisPool;
    }
 
    
//    private static class SingletonHolder{
//    	private final static JedisPoolConfig  jedispool_config;
//    	static{
//    		  jedispool_config = new JedisPoolConfig();
//            //最大活动对象个数
//            jedispool_config.setMaxActive(500);
//    	}
//    	
//        private final static JedisPool instance=new JedisPool(jedispool_config, ip, port);
//    }
//    
//    public static JedisPool getInstance1(){
//        return SingletonHolder.instance;
//    }
    
    public static void close(Jedis jedis){
    	RedisUtil.getInstance().returnResource(jedis);
    }
    public static void set(String key,String value){
    	Jedis jedis = null;
    	try{
    		jedis = getInstance().getResource();
    		jedis.set(key, value);
    	}catch(Exception e){
    		
    	}finally{
    		close(jedis);
    	}
    }
    
    public static Jedis getJedis(){
    	Jedis jedis = null;
    	try{
    		jedis = getInstance().getResource();
    	}catch(Exception e){
    		e.printStackTrace();
    		close(jedis);
    	}
		return jedis;
    }
    
    
    public static void del(String key){
    	Jedis jedis = null;
    	try{
    		jedis = getInstance().getResource();
    		jedis.del(key);
    	}catch(Exception e){
			MyException.writeErr(e, "redisUtil.del删除key错误.");
    	}finally{
    		close(jedis);
    	}
    }
    
    public static String get(String key){
    	Jedis jedis = null;
    	String value="";
    	try{
    		jedis = getInstance().getResource();
    		value=jedis.get(key);
    	}catch(Exception e){
    		return value;
    	}finally{
    		close(jedis);
    	}
    	return value;
    }
    
    public static void setex(String key,String value,int seconds){
    	Jedis jedis = null;
    	try{
    		jedis = getInstance().getResource();
    		jedis.setex(key, seconds, value);
    	}catch(Exception e){
    	}finally{
    		close(jedis);
    	}
    }
    
    /**
     * 缓存中保存对象
     * 
     * @author rfk
     * @date 2014-11-22上午10:23:33
     * @param key
     * @param valueObject
     */
    public static void set(String key, Object valueObject) {
    	String value = JSON.toJSONString(valueObject);
    	Jedis jedis = null;
    	try{
    		jedis = getInstance().getResource();
    		jedis.set(key, value);
    	}catch(Exception e){
    		
    	}finally{
    		close(jedis);
    	}
    }
 
    /**
     * <b>Description:<em><blockquote>
     * 		缓存中保存对象
     *
     * </blockquote></em></b>
     * 
     * @Title: set
     * @param key
     * @param valueObject
     * @param seconds    设置过期时间
     * @author Ran_cc
     * @date 2018年5月25日 
     */
    public static void set(String key, Object valueObject,int seconds) {
    	String value = JSON.toJSONString(valueObject);
    	Jedis jedis = null;
    	try{
    		jedis = getInstance().getResource();
    		jedis.setex(key,seconds, value);
    	}catch(Exception e){
    		
    	}finally{
    		close(jedis);
    	}
    }
    
    public static String getCounter(String key){
    	Jedis jedis = null;
    	String value = "01";
    	try{
    		jedis = getInstance().getResource();
    		if(keyIsExsit(key)){//存在
    			value = jedis.get(key);
    			int value_ = Integer.parseInt(value);
    			if(value_ <  9){
    				value = "0" + (value_+1);
    			}
    		}
    		/*LocalDateTime nowTime = LocalDateTime.now();
    		nowTime.
    		LocalDate now = LocalDate.now();
    		LocalDate tomorrow = now.plusDays(1L);
    		tomorrow.get*/
    		jedis.set(key, value);
    	}catch(Exception e){
    		
    	}finally{
    		close(jedis);
    	}
    	return value;
    }
    
    /**
     * 从缓存中获取value 转化为对象
     * 
     * @author rfk
     * @date 2014-11-22上午10:23:52
     * @param key
     * @param resultClass
     * @return
     */
    public static <T> T get(String key, Class<T> resultClass) {
		log.info("get '" + key + "' data from cache");
		Jedis jedis = null;
    	String value="";
    	try{
    		jedis = getInstance().getResource();
    		value=jedis.get(key);
    	}catch(Exception e){
    		return null;
    	}finally{
    		close(jedis);
    	}
		return JSON.parseObject(value, resultClass);
	}
    
    /**
     * 缓存计数器
     * 
     * @author rfk
     * @date 2014-11-22下午3:12:09
     * @param key
     * @param value
     * @return true:存在  false:
     */
    public static long updateCounter(String key, long value) {
		Jedis jedis = null;
		long count = 0;
    	try{
    		jedis = getInstance().getResource();
    		count = jedis.incrBy(key, value);
    	}catch(Exception e){
    		return 0;
    	}finally{
    		close(jedis);
    	}
		return count;
	}
    
    /**
     * 判断键值是否存在
     * 
     * @author rfk
     * @date 2014-11-22下午3:26:11
     * @param key
     * @return
     */
    public static boolean keyIsExsit(String key) {
		log.info("Is has key:" + key);
		Jedis jedis = null;
		boolean temp = false;
    	try{
    		jedis = getInstance().getResource();
    		temp = jedis.exists(key);
    	}catch(Exception e){
    		return temp;
    	}finally{
    		close(jedis);
    	}
    	return temp;
	}
    
    public static void main(String args[]){
    	Jedis jedis = null;
    	try {
			jedis = getInstance().getResource();



		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(jedis!=null){
				close(jedis);
			}
		}
    }

}

